#!/usr/bin/python
# -*- coding: utf-8 -*-

import gtk, gobject
import threading, thread
import urllib, urllib2, time, datetime, os, gobject

class Main:
	def __init__(self):
	
		self.pluginName = 'eOk'
		self.author = 'Ovidiu D. Niţan'
		self.version = '0.02'
		self.descriere = _('Plugin for searching and downloading music from eOk.ro')

	def start(self, pymaxe):
		try:
			pymaxe.eokmenu
		except:
			pymaxe.eokmenu = gtk.RadioMenuItem(pymaxe.gui.get_object('radiomenuitem1'), 'eOk')
			pymaxe.eokmenu.show()
			pymaxe.gui.get_object('menu2').prepend(pymaxe.eokmenu)
			pymaxe.sites[self.pluginName] = 'eok.ro'
	
	def search(self, pymaxe, string):
		eoklogo = gtk.gdk.pixbuf_new_from_file(__path__[0] + '/eok.png')
		print "[plugin] eOk: searching for " +  string
		sString = {'qs' : string}
		sdata = urllib.urlencode(sString)
		sdata = sdata.replace('+', '%20')
		req = urllib2.Request('http://www.eok.ro/find/search', sdata);
		getdata = urllib2.urlopen(req);
		data = getdata.read();
		try:
			cont = data.split('<div id="track_rating_tr">')
			cont = cont[1].split('<div class="pagination frt">')
			data = cont[0]
			results = data.split('<li style="background-color:')
			results.pop(0)
			#results.pop(len(results)-1)
			for x in results:
				try:
					gid = x.split("/melodie/")
					gid = gid[1].split("/")
					mid = gid[0]
					url = 'http://www.eok.ro/#Artist/dummyartist/melodie/' + mid + '/'
					gname = x.split('<img class="png_play_btn" alt="Play ')
					gname = gname[1].split('" src="http://img.eok.ro/')
					name = '<b>' + gobject.markup_escape_text(gname[0]) + '</b>'
					gobject.idle_add(pymaxe.addToList, [eoklogo, name, '', url])
				except Exception, e:
					#print str(e)
					pass
		except:
			pass

	def getDetails(self, pymaxe, url):
		try:
			data = self.fileData(url)
			if data == False:
				pymaxe.isWorking = False
				gobject.idle_add(self.showDialog, gtk.MESSAGE_ERROR, 'Eroare', 'Nu am putut să citesc informaţiile privind fişierul. Verificaţi dacă aveţi o conexiune la internet şi dacă utilizaţi ultima versiune a pluginului.' )
				gobject.idle_add(pymaxe.restoreState)
				return
			gobject.idle_add(pymaxe.showDetails, data)
		except Exception, e:
			pymaxe.isWorking = False
			gobject.idle_add(self.showDialog, gtk.MESSAGE_ERROR, 'Eroare', 'Nu am putut să citesc informaţiile privind fişierul. Verificaţi dacă aveţi o conexiune la internet şi dacă utilizaţi ultima versiune a pluginului.\n\n\nInformaţii de depanare:\n' + str(e))
			gobject.idle_add(pymaxe.restoreState)
			return False		
		#pymaxe.showDetails(url, titlu, durata, downurl, tip)

	def fileData(self, url):
		gid = url.split('/melodie/')
		gid = gid[1].split('/')
		rawurl = 'http://www.eok.ro/backpipe/getTrack?id=' + gid[0]
		req = urllib2.Request(rawurl);
		getdata = urllib2.urlopen(req);
		data = getdata.read();
		try:	
			gdownurl = data.split("true,{file:'")
			gdownurl = gdownurl[1].split("',snapshot:'")
			downurl = gdownurl[0].replace('\\', '')
			gtitle = data.split('style=\\"margin-top:5px;\\">')
			gtitle = gtitle[1].split('<\\/span><\\/div>')
			titlu = gtitle[0]
			durata = 'N/A'	
								
			data = {"url" : url,
				"titlu" : titlu,
				"durata" : durata,
				"tip" : '.mp3',
				"format" : 'audio',
				"downurl" : downurl}
			return data
		except Exception, e:
			print e
			return False
	
	
	def showDialog(self, type, title, message):
			dialog = gtk.MessageDialog(parent=None, flags=0, type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_CLOSE, message_format=message);
			dialog.set_title(title);
			dialog.run();
			dialog.destroy();

	def uninstall(self, pymaxe):
		pymaxe.eokmenu.destroy()
		del pymaxe.eokmenu
